<template>
  <div class="login-container">
    <el-dialog
      title="授权"
      :visible.sync="$store.state.user.AuthorizationOpen"
      width="800px"
      height="800"
      :before-close="handleClose"
    >
      <!-- 授权上传文件 -->
      <License ref="Authorization" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeOpen">取 消</el-button>
        <!-- <el-button @click="onSubmit()" type="primary">上 传</el-button> -->
        <el-button type="primary" @click="closeOpen">确 定</el-button>
      </span>
    </el-dialog>

    <img class="login-bgimg" src="@/assets/images/login_bgimg_new.png" alt="" />
<!--    <img class="login_logo" src="@/assets/images/login-logo-new.png" />-->
    <div class="login-version" v-if="sysConfig && sysConfig.sysVersion">
      <p class="login-version-text">{{ sysConfig.sysVersion }}</p>
    </div>
    <!-- <div class="login-left">
      <img class="login-banner" src="@/assets/images/login-banner.png" alt="" />
      <div class="login-left-txt" v-if="showTxt">
        在线自动化，可视化系统开发，零代码实现80%的基础功能
        <p class="title1">
          在线自动化，可视化系统开发，零代码实现80%的基础功能
        </p>
      </div>
    </div> -->
    <div class="login-content" style="height: 630px">
      <img
        class="qr-code-icon"
        v-if="active == 1"
        @click="
          active = 2;
          queryWeComInfo();
        "
        src="@/assets/images/qr-code.png"
      />
      <img
        class="qr-code-icon"
        v-if="active == 2"
        @click="active = 1"
        src="@/assets/images/input-login.png"
      />
      <div class="login-form">
        <el-image
          class="login-logo"
          :src="define.comUrl + sysConfig.loginIcon"
          v-if="sysConfig && sysConfig.loginIcon"
        >
          <template slot="error">
            <img
              class="login-logo"
              src="@/assets/images/login_logo.png"
              alt=""
            />
          </template>
        </el-image>
        <div class="login-title">智行数字化平台</div>
        <!-- <img
          class="login-logo"
          src="@/assets/images/login_logo.png"
          alt=""
          v-else
        /> -->
        <div class="login-tab" :class="'active' + active">
          <a
            class="item"
            :class="{ active: active == 1 }"
            @click="active = 1"
            >{{ $t("login.title") }}</a
          >
          <a
            class="item"
            :class="{ active: active == 2 }"
            @click="
              active = 2;
              queryWeComInfo();
            "
            >{{ $t("login.scanTitle") }}</a
          >
        </div>
        <el-form
          v-show="active == 1"
          ref="loginForm"
          :model="loginForm"
          :rules="loginRules"
          autocomplete="on"
          label-position="left"
        >
          <el-form-item prop="account">
            <img
              class="input-icon"
              src="@/assets/images/user-name-icon.png"
              alt=""
            />
            <el-input
              ref="account"
              v-model="loginForm.account"
              :placeholder="$t('login.username')"
              name="account"
              type="text"
              tabindex="1"
              autocomplete="on"
              size="large"
              @change="getConfig"
            ></el-input>
          </el-form-item>
          <!-- <el-form-item class="rule-tip">{{ $t("login.rule") }}</el-form-item> -->
          <el-tooltip
            v-model="capsTooltip"
            :content="$t('login.upper')"
            placement="right"
            manual
          >
            <el-form-item prop="password">
              <img
                class="input-icon"
                src="@/assets/images/pass-word-icon.png"
                alt=""
              />
              <el-input
                ref="password"
                v-model="loginForm.password"
                show-password
                :placeholder="$t('login.password')"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                size="large"
              ></el-input>
              <!-- <div>
                <el-checkbox v-model="isAgreeWith"></el-checkbox>
                <span class="agreement-tips">我已阅读并同意<a>服务协议</a>和<a>个人信息保护政策</a></span>
              </div>
              <div class="account-number-option">
                <el-checkbox v-model="isRemember"></el-checkbox>
                <span>记住密码</span>
                <a>注册账号</a>
                <a>忘记密码</a>
              </div> -->
              <!-- @keyup.enter.native="handleLogin" -->
            </el-form-item>
          </el-tooltip>
          <el-form-item prop="code" v-if="needCode">
            <el-row type="flex" justify="space-between">
              <el-col class="sms-input">
                <el-input
                  v-model="loginForm.code"
                  :placeholder="$t('login.codeTip')"
                  name="code"
                  autocomplete="on"
                  prefix-icon="el-icon-key"
                  size="large"
                >
                </el-input>
              </el-col>
              <el-col class="sms-right code-right">
                <el-tooltip
                  :content="$t('login.changeCode')"
                  placement="bottom"
                >
                  <img
                    id="imgcode"
                    :alt="$t('login.changeCode')"
                    :src="define.comUrl + imgUrl"
                    @click="changeImg"
                  />
                </el-tooltip>
              </el-col>
            </el-row>
          </el-form-item>
          <el-button
            :loading="loading"
            type="primary"
            class="login-btn"
            size="large"
            @click.native.prevent="handleLogin"
            >{{ $t("login.logIn") }}
          </el-button>
        </el-form>
        <div v-show="active == 2" class="login-form-QRCode">
          <!-- <img class="qrcode-img" src="@/assets/images/login_qr.png"> -->
          <div class="selectDeep">
            <el-select
              v-model="qyhCorpId"
              placeholder="请选择"
              @change="loadWeComQrImage"
            >
              <el-option
                v-for="item in qyChatList"
                :key="item.qyhCorpId"
                :label="item.name"
                :value="item.qyhCorpId"
              >
              </el-option>
            </el-select>
          </div>
          <div>
            <span id="qr_login"> </span>
          </div>
          <!--  <p class="qrcode-tip">正在测试,稍后上线</p> -->
        </div>
      </div>
    </div>
    <!--<div class="login-foot">Copyright 引迈信息技术有限公司, All Rights Reserved. 沪ICP备17044791号-1
      助力企业和团队快速实现目标</div>-->
  </div>
</template>

<script>
import {
  getConfig,
  getQyhConfig,
  getLicenseInfo,
  getSystemAddress,
} from "@/api/user";
import { REDIRECT_URI } from "@/constant";
import { isEmpty } from "@/utils/isEmpty";
import { resetRouter } from "@/router";
import License from "@/views/login/com";

export default {
  name: "Login",
  components: {
    License,
  },
  data() {
    return {
      qyhCorpId: "",
      qyChatList: [],
      QYHConfig: {},
      ifScanCode: 0,
      loginForm: {
        account: "",
        password: "",
        code: "",
        origin: "password",
      },
      isAgreeWith: false,
      isRemember: false,
      loginRules: {
        account: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.accountTip"),
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.passwordTip"),
          },
        ],
        code: [
          {
            required: true,
            trigger: "blur",
            message: this.$t("login.codeTip"),
          },
        ],
      },
      imgUrl: "",
      timestamp: "",
      capsTooltip: false,
      loading: false,
      showDialog: false,
      needCode: false,
      codeLength: 4,
      redirect: undefined,
      showTxt: false,
      otherQuery: {},
      active: 1,
      ComputerUrl: "http://gl.bringspring.com/jsbos-web/#/login",
    };
  },
  computed: {
    sysConfig() {
      return this.$store.state.settings.sysConfig;
    },
    loginLoading() {
      return this.$store.state.user.loginLoading;
    },
  },
  watch: {
    loginLoading(val) {
      if (!val) this.loading = false;
    },
    $route: {
      handler: function (route) {
        const query = route.query;
        if (query) {
          this.redirect = query.redirect;
          this.otherQuery = this.getOtherQuery(query);
        }
      },
      immediate: true,
    },
  },
  created() {
    // 判断是否微信浏览器打开
    this.$route.query.applicationId = "all";
    console.log("created",this.$route.query);
    var ua = navigator.userAgent.toLowerCase();
    var isWeixin = ua.indexOf("micromessenger") !== -1;
    const code = this.getUrlParam("code");
    // this.getCode();
    if (isWeixin) {
      if (!code) {
        // 获取code(临时授权码)
        this.getCode();
      }
    }
    if (code) {
      // 重定向（重新加载一次该页面第二次获取到code）
      this.qywxLoginByCode(code);
    }
    const _this = this;
    document.onkeydown = function (e) {
      const { keyCode } = e;
      if (keyCode === 13) {
        _this.handleLogin();
      }
    };
    if (this.needCode) this.changeImg();
  },
  mounted() {
    this.$store.commit("user/SET_LOGIN_LOADING", false);
    this.setShowTxt();
    window.onresize = () => {
      this.setShowTxt();
    };

    this.getLicense();
  },
  destroyed() {
    document.onkeydown = function (e) {
      const { keyCode } = e;
      if (keyCode === 13) {
      }
    };
  },
  methods: {
    async getLicense() {
      await getLicenseInfo().then((res) => {
        console.log("res", res);
        if (!res.data.isExist) {
          this.$store.commit("user/SET_AUTHORIZATIONOPEN", true);
        }
      });
    },
    setShowTxt() {
      if (document.documentElement.clientHeight <= 840) {
        this.showTxt = false;
      } else {
        this.showTxt = true;
      }
    },
    checkCapslock(e) {
      const { key } = e;
      this.capsTooltip = key && key.length === 1 && key >= "A" && key <= "Z";
    },
    getConfig(val) {
      if (!val) return;
      getConfig(this.loginForm.account).then((res) => {
        this.needCode = !!res.data.enableVerificationCode;
        if (this.needCode) {
          this.codeLength = res.data.verificationCodeNumber || 4;
          this.changeImg();
        }
      });
    },
    handleLogin() {
      if (this.loading) return;
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.$store.commit("user/SET_LOGIN_LOADING", true);
          const query = {
            ...this.loginForm,
            timestamp: this.timestamp,
          };
          this.$store
            .dispatch("user/login", query)
            .then((res) => {
              this.$store.dispatch("tagsView/closeAll");
              //重新获取系统菜单
              let contractId = "";
              this.$store.dispatch("user/getInfo", "").then(async (rese) => {
                resetRouter();
                const accessRoutes = await this.$store.dispatch(
                  "permission/generateRoutes",
                  rese
                );
                this.$router.addRoutes(accessRoutes);
                this.$store.commit("contract/SET_EXEC_DATE", undefined);
                this.$router.push({
                  // 首页home   调整到客户资源界面默认
                  // this.redirect ||
                  path: "/dashboard",
                  query: {
                    applicationId: contractId,
                    // otherQuery: this.otherQuery,
                  },
                });
              });
              // this.$router.push({
              //   // 首页/dashboard   调整到客户资源界面默认
              //   path: this.redirect || "/dashboard",
              //   query: this.otherQuery,
              // });
            })
            .catch(() => {
              this.$store.commit("user/SET_LOGIN_LOADING", false);
            });
        } else {
          return false;
        }
      });
    },
    changeImg() {
      let timestamp = Math.random();
      this.timestamp = timestamp;
      this.imgUrl = `/api/oauth/ImageCode/${this.codeLength || 4}/${timestamp}`;
    },
    getOtherQuery(query) {
      return Object.keys(query).reduce((acc, cur) => {
        if (cur !== "redirect") {
          acc[cur] = query[cur];
        }
        return acc;
      }, {});
    },
    qywxLoginByCode(code) {
      const _stateArr = this.getStateAll();
      let _qyhCorpId = _stateArr.corpId;
      let _qyhAgentId = _stateArr.agentId;
      localStorage.setItem("_qyhCorpId", _qyhCorpId);
      localStorage.setItem("_qyhAgentId", _qyhAgentId);
      console.log("======", _qyhCorpId, _qyhAgentId);

      this.loading = true;
      this.$store.commit("user/SET_LOGIN_LOADING", true);
      // let _qyhCorpId = this.getUrlParam("qyhCorpId");
      // _qyhCorpId = _qyhCorpId ? _qyhCorpId : this.getUrlParam("state");
      // _qyhCorpId = 'wwc0366cea7d993696';
      this.qyhCorpId = _qyhCorpId;
      const paramCode = {
        code: code,
        qyhCorpId: _qyhCorpId,
        qyhAgentId: _qyhAgentId,
      };
      console.log("paramCode---", paramCode);
      this.$store
        .dispatch("user/loginByWeCom", paramCode)
        .then((res) => {
          this.$router.push({
            // 首页/dashboard   调整到客户资源界面默认
            path: this.redirect || "/dashboard",
            query: this.otherQuery,
          });
        })
        .catch(() => {
          this.$store.commit("user/SET_LOGIN_LOADING", false);
        });
    },
    getCode() {
      //新逻辑
      // 获取路径参数
      const query = this.$route.query;
      let _qyhCorpId = "";
      let _qyhAgentId = "";
      if (query.qyhCorpId) {
        _qyhCorpId = query.qyhCorpId;
      } else if (localStorage.getItem("_qyhCorpId")) {
        _qyhCorpId = localStorage.getItem("_qyhCorpId");
      }
      if (query.qyhAgentId) {
        _qyhAgentId = query.qyhAgentId;
      } else if (localStorage.getItem("_qyhAgentId")) {
        _qyhAgentId = localStorage.getItem("_qyhAgentId");
      }
      let redirect_uri = "";
      // let redirect_uri = encodeURIComponent(redirect_uri_query.split('#')[0])
      this.qyhCorpId = _qyhCorpId;

      if (_qyhCorpId && _qyhAgentId) {
        getSystemAddress("pc").then((res) => {
          // redirect_uri = encodeURIComponent(
          //   "https://gl.bringspring.com/zhangchengxin/#/login"
          // );
          redirect_uri = encodeURIComponent(res.msg);
          const url = "https://open.weixin.qq.com/connect/oauth2/authorize";
          const wx_url = `${url}?appid=${_qyhCorpId}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${_qyhCorpId}&agentid=${_qyhAgentId}#wechat_redirect`;
          window.location.replace(wx_url);
        });
      } else {
        this.$message.warning("缺少自动登录必要参数，请手动或扫码登录。");
      }
      // // 获取路径参数
      // const query = this.$route.query;
      // const _qyhCorpId = query.qyhCorpId;
      // this.qyhCorpId = _qyhCorpId;

      // // 获取code(临时授权码)的url动态
      // getQyhConfig()
      //   .then((res) => {
      //     if (res.data) {
      //       var weComList = res.data;
      //       var weCom = weComList.filter((v) => {
      //         return v.qyhCorpId == _qyhCorpId;
      //       })[0];
      //       if (weCom) {
      //         // 构造第三方应用oauth2链接 https://developer.work.weixin.qq.com/document/path/91120
      //         const url = "https://open.weixin.qq.com/connect/oauth2/authorize";
      //         const appid = weCom.qyhCorpId; //企业id
      //         const agentid = weCom.qyhAgentId; //应用id
      //         const redirect_uri = encodeURIComponent(weCom.qyhComputerUrl); // 授权后重定向的回调链接地址s
      //         const wx_url = `${url}?appid=${appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=${appid}&agentid=${agentid}#wechat_redirect`;
      //         window.location.replace(wx_url);
      //       } else {
      //         this.$message.warning("自动登录失败，系统配置企业ID不存在");
      //       }
      //     } else {
      //       this.$message.warning("获取企业微信配置失败");
      //       console.error("未获取自动登录企业微信配置");
      //     }
      //   })
      //   .catch((err) => {
      //     console.error(err);
      //   });
    },
    //获取地址栏url后的参数值
    getUrlParam(key) {
      var href = window.location.href;
      var url = href.split("?");
      if (url.length <= 1) {
        return "";
      }
      var params = url[1].split("&");

      for (var i = 0; i < params.length; i++) {
        var param = params[i].split("=");
        if (key == param[0]) {
          return param[1];
        }
      }
    },
    /**解析企业微信扫码或自动登录回调地址携带state参数 */
    getStateAll() {
      const _state = this.getUrlParam("state"); // wwc0366cea7d993696_1000034 或 wwc0366cea7d993696_1000034#/login
      console.log("statestatestate", _state);
      const _stateArr = _state.split("#")[0].split("_");
      return {
        corpId: _stateArr[0],
        agentId: _stateArr[1],
      };
    },
    /**获取企业微信公司配置 */
    queryWeComInfo() {
      getQyhConfig()
        .then((res) => {
          if (this.isEmpty(res.data)) {
            this.$message.warning("企业微信配置为空");
          } else {
            this.qyChatList = res.data;
            console.log("----", this.qyChatList);
            this.loadWeComQrImage();
          }
        })
        .catch((err) => console.log(err));
    },
    /**加载企业微信二维码 */
    loadWeComQrImage() {
      console.log("----", this.qyChatList);
      if (this.qyhCorpId && !this.isEmpty(this.qyhCorpId)) {
        this.QYHConfig = this.qyChatList.filter((v) => {
          return v.qyhCorpId == this.qyhCorpId;
        })[0];
      } else {
        this.QYHConfig = this.qyChatList[0];
        this.qyhCorpId = this.QYHConfig.qyhCorpId;
      }

      var wwLogin = new WwLogin({
        id: "qr_login",
        appid: this.QYHConfig.qyhCorpId,
        agentid: this.QYHConfig.qyhAgentId,
        redirect_uri: encodeURIComponent(this.QYHConfig.qyhComputerUrl),
        state: this.QYHConfig.qyhCorpId + "_" + this.QYHConfig.qyhAgentId,
        href: "",
        lang: "zh",
      });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          // done();
          this.$store.commit("user/SET_AUTHORIZATIONOPEN", false);
        })
        .catch((_) => {});
    },
    closeOpen() {
      this.$store.commit("user/SET_AUTHORIZATIONOPEN", false);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";

/* 利用穿透，设置input边框隐藏 */
.selectDeep >>> .el-input__inner {
  border: 0;
}
</style>
